'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【debugIncomeRecord】调试收入记录:', event);
  
  const { recordId } = event;
  
  try {
    // 1. 查找收入记录
    const incomeRes = await db.collection('task_income_records')
      .doc(recordId)
      .get();
    
    console.log('【debugIncomeRecord】收入记录:', incomeRes.data);
    
    if (!incomeRes.data || incomeRes.data.length === 0) {
      return {
        code: 404,
        msg: '收入记录不存在',
        data: null
      };
    }
    
    const incomeRecord = incomeRes.data[0];
    
    // 2. 查找发布者信息
    const publisherRes = await db.collection('uni-id-users')
      .doc(incomeRecord.publisher_id)
      .get();
    
    console.log('【debugIncomeRecord】发布者信息:', publisherRes.data);
    
    // 3. 查找接收者信息（如果有）
    let receiverInfo = null;
    if (incomeRecord.receiver_id) {
      const receiverRes = await db.collection('uni-id-users')
        .doc(incomeRecord.receiver_id)
        .get();
      
      console.log('【debugIncomeRecord】接收者信息:', receiverRes.data);
      receiverInfo = receiverRes.data[0];
    }
    
    // 4. 查找发布者的任务列表
    const tasksRes = await db.collection('taskList')
      .where({ publisher_id: incomeRecord.publisher_id })
      .orderBy('publish_time', 'desc')
      .limit(5)
      .get();
    
    console.log('【debugIncomeRecord】发布者的任务列表:', tasksRes.data);
    
    return {
      code: 200,
      msg: '调试完成',
      data: {
        incomeRecord: {
          id: incomeRecord._id,
          task_id: incomeRecord.task_id,
          publisher_id: incomeRecord.publisher_id,
          receiver_id: incomeRecord.receiver_id,
          reward_amount: incomeRecord.reward_amount,
          status: incomeRecord.status,
          create_time: incomeRecord.create_time,
          complete_time: incomeRecord.complete_time
        },
        publisher: publisherRes.data[0] ? {
          id: publisherRes.data[0]._id,
          nickname: publisherRes.data[0].nickname,
          username: publisherRes.data[0].username,
          balance: publisherRes.data[0].balance
        } : null,
        receiver: receiverInfo ? {
          id: receiverInfo._id,
          nickname: receiverInfo.nickname,
          username: receiverInfo.username,
          balance: receiverInfo.balance
        } : null,
        tasks: tasksRes.data.map(task => ({
          id: task._id,
          title: task.title,
          status: task.status,
          reward: task.reward,
          receiver_id: task.receiver_id,
          receiver_name: task.receiver_name
        }))
      }
    };
    
  } catch (error) {
    console.error('【debugIncomeRecord】调试失败:', error);
    return {
      code: 500,
      msg: '调试失败',
      error: error.message
    };
  }
};